package com.nclg.exam.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nclg.exam.dto.ExamFinishedPaperDto;
import com.nclg.exam.dto.ExamPaperDto;
import com.nclg.exam.dto.PaperHistoryDto;
import com.nclg.exam.entity.TUserAnswer;
import com.nclg.exam.entity.TUserPaper;
import com.nclg.exam.mapper.ExamMapper;
import com.nclg.exam.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@Transactional
public class ExamServiceImpl implements ExamService {

    @Autowired
    private ExamMapper examMapper;

    /**
     * 查询正在考试的试卷
     * @param page
     * @param limit
     * @return
     */
    @Override
    public PageInfo<ExamPaperDto> selectExamPaperByPage(int page, int limit) {
        PageHelper.startPage(page,limit);
        List<ExamPaperDto> list = examMapper.selectExamPaperByPage();
        return new PageInfo<>(list);
    }

    /**
     * 查询考试历史
     * @param dto
     * @return
     */
    @Override
    public PageInfo<PaperHistoryDto> selectExamFinishedPaperByPage(ExamFinishedPaperDto dto) {
        PageHelper.startPage(dto.getPage(),dto.getLimit());
        List<PaperHistoryDto> list = examMapper.selectExamFinishedPaperByPage(dto.getUId());
        return new PageInfo<>(list);
    }

    /**
     * 是否提交过试卷
     * @param pId
     * @param uId
     * @return
     */
    @Override
    public boolean selectIsFinished(Long pId, Long uId) {
        return examMapper.selectIsFinished(pId, uId) > 0 ? true : false;
    }

    /**
     * 提交试卷
     * @param pId
     * @param uId
     * @param score
     * @param answerJson
     * @return
     */
    @Override
    public boolean insertUserPaperAndAnswer(Long pId, Long uId, BigDecimal score, String answerJson) {
        //插入试卷
        TUserPaper userPaper = new TUserPaper();
        userPaper.setPId(pId);
        userPaper.setUId(uId);
        userPaper.setUpChoicescore(score);
        boolean isTrue = examMapper.insertUserPaper(userPaper) > 0 ? true : false;
        if (!isTrue) return false;
        //插入用户答案
        TUserAnswer userAnswer = new TUserAnswer();
        userAnswer.setPId(pId);
        userAnswer.setUId(uId);
        userAnswer.setUpId(userPaper.getUpId());
        userAnswer.setUaAnswer(answerJson);
        return examMapper.insertUserAnswer(userAnswer) > 0 ? true : false;
    }

    /**
     * 查询用户答案
     * @param upId
     * @return
     */
    @Override
    public String selectUserAnswer(Long upId) {
        return examMapper.selectUserAnswer(upId);
    }

}
